<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;
use common\models\Customer;
use backend\models\CustomerForm;
use backend\models\CustomerDataForm;
use common\models\CustomerIntention;
use backend\models\IntentionForm;
use common\models\Product;
use common\models\Department;
use common\models\Employees;
use common\models\User;

/**
 * Customer controller
 */
class CustomerController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['create', 'datalist', 'intention', 'view', 'getintention', 'getemployee', 'assigntrans', 'removeintention'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /*
    * 新建客户
     */
    public function actionCreate($id=null)
    {
        if(!Yii::$app->user->can('addCustomer')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }

        $model = new CustomerForm($id);
        if ($id) {
            $model->scenario = 'update';
        } else {
            $model->scenario = 'create';
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->addOrUpdate()) {

                return $this->redirect(['customer/datalist']);
            }
        }

        return $this->render('create', ['model' => $model]);
    }

    /*
    * 客户列表
     */
    public function actionDatalist()
    {
        if(!Yii::$app->user->can('customerList')){
            throw new ForbiddenHttpException('对不起，您现在还没获得此操作的权限');
        }
        
        $data_form = new CustomerDataForm;
        $data = Customer::find();
        if ($data_form->load(Yii::$app->request->get()) && $data_form->validate()) {
            $data = $data_form->query();
        }

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => '10']);
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $product_arr = Product::find()->where(['status' => Product::ACTIVE_STATUS])->asArray()->all();
        $product = ArrayHelper::map($product_arr, 'id', 'name');

        return $this->render('datalist', ['model' => $model, 'pages' => $pages, 'product' => $product]);
    }

    /*
    * 新增意向产品
     */
    public function actionIntention($uid=null)
    {       
        $model = new IntentionForm;
        $model->scenario = 'create';

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->addIntention($uid)) {

                return $this->redirect(['customer/datalist']);
            }
        }
        $product_arr = Product::find()->where(['status' => Product::ACTIVE_STATUS])->asArray()->all();
        $product = ArrayHelper::map($product_arr, 'id', 'name');
        $username = Customer::findOne($uid)->username;
        $depart = Department::find()->select(['id', 'name'])->asArray()->all();
        $depart = ArrayHelper::map($depart, 'id', 'name');

        return $this->render('intention', ['model' => $model, 'uid' => $uid, 'product' => $product, 'username' => $username, 'depart' => $depart]);
    }

    /*
    * 查看意向产品
     */
    // public function actionView($uid=null)
    // {
    //     $model = new IntentionForm;
    //     $model->scenario = 'update';
    //     $customer_intention = CustomerIntention::find()->where(['cid' => $uid])->all();
    //     $product = [];
    //     if ($customer_intention) {
    //         foreach ($customer_intention as $val) {
    //             $product_arr = Product::find()->where(['status' => Product::ACTIVE_STATUS, 'id' => $val->pid])->one();
    //             array_push($product, $product_arr);
    //         }
    //     }
    //     $username = Customer::findOne($uid)->username;
    //     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    //         if ($model->updateIntention($uid)) {
    //             Yii::$app->session->setFlash('success', '意向信息更新成功');
                
    //             return $this->redirect(['customer/datalist']);
    //         }
    //     }

    //     return $this->render('view', ['model' => $model, 'product' => $product, 'username' => $username, 'uid' => $uid]);
    // }
    public function actionView($uid=null)
    {   
        $id = Yii::$app->user->id;
        $eid = User::findOne($id)->eid;
        $data = CustomerIntention::find()->where(['cid' => $uid])->andWhere(['status' => CustomerIntention::ACTIVE_STATUS])->andWhere(['or', ['=', 'create_user', $id], ['=', 'trans_user', $eid]]);

        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => '10']);
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $username = Customer::findOne($uid)->username;
        $employee = Employees::find()->all();
        $employee = ArrayHelper::map($employee, 'id', 'realname');
        $depart = Department::find()->select(['id', 'name'])->asArray()->all();
        $depart = ArrayHelper::map($depart, 'id', 'name');

        return $this->render('viewlist', ['uid' => $uid, 'model' => $model, 'pages' => $pages, 'username' => $username, 'employee' => $employee, 'depart' => $depart]);
    }

    /*
    * 获取意向产品信息
     */
    public function actionGetintention()
    {
        $pid = trim(Yii::$app->request->get()['pid']);
        $uid = trim(Yii::$app->request->get()['uid']);
        $customer_intention = CustomerIntention::find()->where(['pid' => $pid, 'cid' => $uid])->one();
        if ($customer_intention) {

            return JSON::encode([
                    'flag' => true,
                    'data' => $customer_intention
                ]);
        } else {

            return JSON::encode([
                    'flag' => false
                ]);
        }
    }

    /*
    * 获取部门的员工
     */
    public function actionGetemployee()
    {
        $did = trim(Yii::$app->request->get()['did']);
        $employee = Employees::find()->joinWith('empdepart')->where(['emp_depart.did' => $did])->asArray()->all();
        $employee = ArrayHelper::map($employee, 'id', 'realname');
        if ($employee) {

            return JSON::encode([
                    'flag' => true,
                    'data' => $employee
                ]);
        } else {

            return JSON::encode([
                    'flag' => false
                ]);
        }
    }

    /*
    * 修改接待人员
     */
    public function actionAssigntrans($uid=null)
    {
        $model = new IntentionForm;
        $model->scenario = 'assigntrans';
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->assign()) {

                return $this->redirect(['customer/view', 'uid' => $uid]);
            }
        }
    }

    /*
    * 移除意向客户
     */
    public function actionRemoveintention()
    {
        $intid = trim(Yii::$app->request->get()['intid']);
        $customer_intention = CustomerIntention::findOne($intid);
        if ($customer_intention) {
            $customer_intention->status = CustomerIntention::DISABLE_STATUS;
            if ($customer_intention->save(false)) {

                return JSON::encode([
                    'flag' => true
                ]);
            }
        }

        return JSON::encode([
                'flag' => false
            ]);
    }

}    